import MapLayer from "./MapLayer";
import BaseTank from "./BaseTank";
import { log_debug } from "./Utils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class BlockWall extends cc.Component {
    @property(cc.Boolean)
    in_reinforce: boolean = false;

    mapLayer: MapLayer;

    init() {
        let children = this.node.children;
        for (let i = 0; i < children.length; ++i) {
            children[i].active = false;
        }

        this.mapLayer = cc.find("/Canvas/GameLayer/MapLayer").getComponent(MapLayer);
    }

    tryDestory(box: cc.Rect, tank: BaseTank) {
        let flag = false;

        // 加固阶段特殊处理
        if (this.in_reinforce) {
            if (tank.isEnemy) {
                return flag;
            }

            if (tank.level < 2) {
                return flag;
            }
        }

        let blacks = this.node.children;
        let position = this.node.position;

        for (let i = 0; i != blacks.length; ++i) {
            // 将黑块坐标变换为相对MapLayer的坐标
            let preBox = blacks[i].getBoundingBox();
            let tranBox = new cc.Rect(
                preBox.xMin + position.x,
                preBox.yMin + position.y,
                preBox.xMax - preBox.xMin,
                preBox.yMax - preBox.yMin
            );
            if (!blacks[i].active && tranBox.intersects(box)) {
                blacks[i].active = true;
                flag = true;
            }
        }

        if (this._isDestory()) {
            this.node.destroyAllChildren();
            this.node.destroy();
        }

        return flag;
    }

    _isDestory() {
        // 不根据黑块来处理了 直接销毁整个block
        let blacks = this.node.children;
        for (let i = 0; i != blacks.length; ++i) {
            if (blacks[i].active) {
                return true;
            }
        }
        return false;
    }
}